package com.lancoo.ai.test.base.lib;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

public class JsonUtil {
    public static <T> T parseJson(String json, Class<T> classOfT) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        try {
            return gson.fromJson(json, classOfT);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 例：new TypeToken<ArrayList<YourClass>>() {} 或 new TypeToken<HashMap<Integer, String>>() {}
    public static <T> T parseJson(String json, TypeToken<T> typeToken) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        try {
            return gson.fromJson(json, typeToken.getType());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String toJson(Object o) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        try {
            return gson.toJson(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toJson(String[] paramNames, String[] paramValues) {
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            map.put(paramNames[i], paramValues[i]);
        }
        return toJson(map);
    }
}
